<?php
require_once 'config.php';
require_once 'auth_check.php';

$errors = [];
$success = '';

// 获取当前用户的安全问题
$stmt = $pdo->prepare("SELECT security_question FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$current_question = $stmt->fetchColumn();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取表单数据
    $old_password = $_POST['old_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    $new_question = clean_input($_POST['new_question']);
    $new_answer = clean_input($_POST['new_answer']);

    try {
        // 验证旧密码
        $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user = $stmt->fetch();

        if (!password_verify($old_password, $user['password'])) {
            throw new Exception('旧密码不正确');
        }

        // 密码修改验证
        if (!empty($new_password)) {
            if (strlen($new_password) < 8) {
                throw new Exception('新密码至少需要8个字符');
            }
            if ($new_password !== $confirm_password) {
                throw new Exception('两次输入的新密码不一致');
            }
            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
        }

        // 密保问题修改验证
        if (!empty($new_question)) {
            if (empty($new_answer)) {
                throw new Exception('修改安全问题必须提供答案');
            }
            if (strlen($new_answer) < 2) {
                throw new Exception('安全答案至少需要2个字符');
            }
            $answer_hash = password_hash(strtolower(trim($new_answer)), PASSWORD_DEFAULT);
        }

        // 构建更新语句
        $updates = [];
        $params = [];

        if (!empty($new_password)) {
            $updates[] = 'password = ?';
            $params[] = $password_hash;
        }

        if (!empty($new_question)) {
            $updates[] = 'security_question = ?';
            $params[] = $new_question;
            $updates[] = 'security_answer_hash = ?';
            $params[] = $answer_hash;
        }

        if (!empty($updates)) {
            $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
            $params[] = $_SESSION['user_id'];
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            $success = '账户信息更新成功';
        } else {
            throw new Exception('未修改任何信息');
        }

    } catch (Exception $e) {
        $errors[] = $e->getMessage();
    }
}

include 'includes/header.php';
?>

<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h4>账户安全设置</h4>
                </div>
                <div class="card-body">
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <?php foreach ($errors as $error): ?>
                                <div><?= htmlspecialchars($error) ?></div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <?php if (($success)): ?>
                        <div class="alert alert-success">
                            <?= htmlspecialchars($success) ?>
                        </div>
                    <?php endif; ?>

                    <form method="post">
                        <!-- 密码修改部分 -->
                        <div class="mb-4">
                            <h5>修改密码</h5>
                            <div class="mb-3">
                                <label class="form-label">当前密码</label>
                                <div class="input-group">
                                    <input type="password" 
                                        class="form-control" 
                                        name="old_password" 
                                        id="oldPassword"
                                        placeholder="请输入旧密码" 
                                        required>
                                    <button type="button" 
                                            class="btn btn-outline-secondary toggle-password">
                                        <i class="bi bi-eye-slash"></i>
                                    </button>   
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">新密码</label>
                                <div class="input-group">
                                    <input type="password" 
                                        class="form-control password-strength" 
                                        name="new_password" 
                                        id="changePassword"
                                        placeholder="请输入新密码（至少8位）" 
                                        required
                                        minlength="8"
                                        data-bs-toggle="popover"
                                        data-bs-custom-class="password-popover custom-popover"
                                        data-bs-placement="auto"
                                        data-bs-trigger="focus"
                                        data-bs-html="true"
                                        data-bs-title="密码要求"
                                        data-bs-content="<ul class='list-unstyled mb-0'>
                                            <li id='popover-length-change' class='text-danger'><i class='bi bi-x-circle-fill'></i> 至少8个字符</li>
                                            <li id='popover-lowercase-change' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含小写字母</li>
                                            <li id='popover-uppercase-change' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含大写字母</li>
                                            <li id='popover-number-change' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含数字</li>
                                        </ul>">
                                    <button type="button" 
                                            class="btn btn-outline-secondary toggle-password">
                                        <i class="bi bi-eye-slash"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">确认新密码</label>
                                <div class="input-group">
                                <input type="password" 
                                       class="form-control" 
                                       name="confirm_password" 
                                       id="confirmPassword"
                                       placeholder="请再次输入新密码" 
                                       required
                                       minlength="8">
                                <button type="button" 
                                        class="btn btn-outline-secondary toggle-password">
                                    <i class="bi bi-eye-slash"></i>
                                </div>

                            </div>
                        </div>

                        <!-- 密保问题修改部分 -->
                        <div class="mb-4">
                            <h5>修改密保设置</h5>
                            <div class="mb-3">
                                <label class="form-label">当前安全问题</label>
                                <input type="text" 
                                       class="form-control" 
                                       value="<?= htmlspecialchars($current_question) ?>" 
                                       readonly>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">新安全问题（留空不修改）</label>
                                <select class="form-select" 
                                        name="new_question" 
                                        id="security_question">
                                    <option value="">请选择安全问题</option>
                                    <option value="您母亲的名字是什么？">您母亲的名字是什么？</option>
                                    <option value="您的出生城市是哪里？">您的出生城市是哪里？</option>
                                    <option value="自定义问题">自定义问题...</option>
                                </select>
                            </div>
                            <div class="mb-3" id="custom-question-container" style="display: none;">
                                <input type="text" 
                                       class="form-control" 
                                       name="new_question_custom" 
                                       placeholder="请输入自定义安全问题">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">新安全问题答案</label>
                                <input type="text" 
                                       class="form-control" 
                                       name="new_answer" 
                                       placeholder="如果修改安全问题，必须填写">
                            </div>
                        </div>
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary">保存更改</button>
                            <a href="profile.php" class="btn btn-secondary">返回个人中心</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 仅用于change_password.php的密码强度验证
    document.addEventListener('DOMContentLoaded', function() {
        const passwordInput = document.getElementById('changePassword');
        if (passwordInput) {
            const popover = new bootstrap.Popover(passwordInput, {
                container: 'body',
                customClass: 'password-popover custom-popover',
                sanitize: false
            });
            
            function updatePasswordRequirements(value) {
                const requirements = {
                    length: value.length >= 8,
                    lowercase: /[a-z]/.test(value),
                    uppercase: /[A-Z]/.test(value),
                    number: /\d/.test(value)
                };

                Object.keys(requirements).forEach(key => {
                    const element = document.getElementById('popover-'+key+'-change');
                    if (element) {
                        const isValid = requirements[key];
                        element.classList.toggle('text-success', isValid);
                        element.classList.toggle('text-danger', !isValid);
                        const icon = element.querySelector('i');
                        if (icon) {
                            icon.className = isValid ? 'bi bi-check-circle-fill' : 'bi bi-x-circle-fill';
                        }
                    }
                });
            }
            
            passwordInput.addEventListener('shown.bs.popover', function() {
                updatePasswordRequirements(this.value);
            });
            
            passwordInput.addEventListener('input', function(e) {
                updatePasswordRequirements(e.target.value);
            });
        }
    });
</script>
<?php include 'includes/footer.php'; ?>